﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Newtonsoft.Json;

namespace VisionCore
{
    public class DAL<T> where T : new()
    {
        /// <summary>
        /// 文件名称
        /// </summary>
        public string FileName { get; set; } = "";

        /// <summary>
        /// 文件路径
        /// </summary>
        public string FileDir { get; set; } = "";

        /// <summary>
        /// 文件夹名称
        /// </summary>
        public string FolderName { get; set; } = "";

        public DAL()
        {

        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="vType">文件名</param>
        /// <param name="vRecipe">文件夹名称</param>
        public DAL(ParamType vType, string vRecipe = "")
        {
            FileDir = Environment.CurrentDirectory + string.Format(@"\Parameter\{0}\", vType.ToString());
            FileName = string.Format("{0}.pra", vType.ToString());
            FolderName = vRecipe;
        }

        /// <summary>
        /// 载入目录下的文件夹(固定文件夹)
        /// </summary>
        /// <returns>载入数据</returns>
        public T Load()
        {
            T tT;
            if (Exists(FolderName))
            {
                string tData = File.ReadAllText(FileDir + FolderName + "\\" + FileName);
                tT = JsonConvert.DeserializeObject<T>(tData);
            }
            else
            {
                tT = new T();
                Add(tT, FolderName);
            }

            return tT;
        }

        /// <summary>
        /// 载入目录下的文件夹(不固定)
        /// </summary>
        /// <param name="vRecipe">文件夹名</param>
        /// <returns></returns>
        public T Load(string vRecipe)
        {
            T tT;
            if (Exists(vRecipe))
            {
                string tData = File.ReadAllText(FileDir + vRecipe + "\\" + FileName);
                tT = JsonConvert.DeserializeObject<T>(tData);
            }
            else
            {
                tT = new T();
                Add(tT, vRecipe);
            }
            return tT;
        }

        /// <summary>
        /// 查询文件夹是否存在
        /// </summary>
        /// <param name="vRecipe"></param>
        /// <returns></returns>
        private bool Exists(string vRecipe)
        {
            string path = string.Format(@"{0}/{1}", FileDir, vRecipe);
            return Directory.Exists(path);
        }


        /// <summary>
        /// 获取目录下所有文件名
        /// </summary>
        /// <param name="vDir"></param>
        /// <returns></returns>
        public List<string> GetRecipes()
        {
            DirectoryInfo tDir = new DirectoryInfo(FileDir);
            List<DirectoryInfo> tDirList = tDir.GetDirectories().ToList();
            List<string> tList = new List<string>();

            for (int i = 0; i < tDirList.Count; i++)
            {
                {
                    tList.Add(tDirList[i].Name);
                }
            }

            return tList;
        }

        public void Add(T vT, string vRecipe)
        {
            if (Exists(vRecipe))
            {
                return;
            }

            Save(vT, vRecipe);
        }

        object objLock = new object();
        /// <summary>
        /// 保存文件(固定路径)
        /// </summary>
        /// <param name="vT"></param>
        public void Save(T vT)
        {
            lock(objLock)
            {
                CreateDir(FolderName);
                string tData = JsonConvert.SerializeObject(vT, Formatting.Indented);
                File.WriteAllText(FileDir + FolderName + "\\" + FileName, tData);
            }
        }

        /// <summary>
        /// 保存文件(不固定路径)
        /// </summary>
        /// <param name="vT">数据</param>
        /// <param name="vRecipeName">文件夹名称</param>
        public void Save(T vT, string vRecipeName)
        {
            CreateDir(vRecipeName);
            string tData = JsonConvert.SerializeObject(vT, Formatting.Indented);
            string path = string.Format(@"{0}{1}\", FileDir, vRecipeName);
            File.WriteAllText(path + FileName, tData);
        }

        /// <summary>
        /// 删除文件夹(不固定路径)
        /// </summary>
        /// <param name="vRecipe"></param>
        public void Delete(string vRecipe)
        {
            string strDir = FileDir + vRecipe;
            if (Directory.Exists(strDir))
            {
                try
                {
                    Directory.Delete(strDir, true);
                }
                catch (Exception ex)
                {

                }
            }
        }

        /// <summary>
        /// 删除文件夹(固定路径)
        /// </summary>
        public void Delete()
        {
            string strDir = FileDir + FolderName;
            if (Directory.Exists(strDir))
            {
                try
                {
                    Directory.Delete(strDir, true);
                }
                catch (Exception ex)
                {

                }
            }
        }

        /// <summary>
        /// 创建目录
        /// </summary>
        /// <param name="vRecipe">文件夹名称</param>
        private void CreateDir(string vRecipe)
        {
            if (!Directory.Exists(FileDir + vRecipe + "\\"))
            {
                Directory.CreateDirectory(FileDir + vRecipe + "\\");
            }
        }

        /// <summary>
        /// 复制文件夹
        /// </summary>
        /// <param name="vSource">来源文件夹</param>
        /// <param name="vDst">目标文件夹</param>
        public void Copy(string vSource, string vDst)
        {
            string tSource = FileDir + "\\" + vSource;
            string tDst = FileDir + "\\" + vDst;

            string[] tSourceFiles = Directory.GetFiles(tSource);
            if (string.IsNullOrEmpty(vDst) || tSourceFiles.Length < 1)
            {
                return;
            }

            if (!Directory.Exists(tDst))
            {
                Directory.CreateDirectory(tDst);
            }

            for (int i = 0; i < tSourceFiles.Length; i++)
            {
                String src = tSourceFiles[i];
                File.Copy(src, src.Replace(tSource, tDst), true);
            }
        }

        public void Copy(string vSource)
        {
            string tSource = FileDir + "\\" + vSource;
            string tDst = FileDir + "\\" + FolderName;

            string[] tSourceFiles = Directory.GetFiles(tSource);
            if (string.IsNullOrEmpty(FolderName) || tSourceFiles.Length < 1)
            {
                return;
            }

            if (!Directory.Exists(tDst))
            {
                Directory.CreateDirectory(tDst);
            }

            for (int i = 0; i < tSourceFiles.Length; i++)
            {
                String src = tSourceFiles[i];
                File.Copy(src, src.Replace(tSource, tDst), true);
            }
        }

        /// <summary>
        /// 复制文件夹到其他文件夹
        /// </summary>
        /// <param name="vSource">来源文件夹</param>
        /// <param name="vDst">目标文件夹</param>
        public void CopyToHistoryFile(string vSource, string vDst)
        {
            string tSource = FileDir + "\\" + vSource;
            string tDst = string.Format(@"{0}\{1}", ParameterHelper.SysParam.FilePath.LogFileDir, vDst.ToString());
            //string tDst = $"E:\\Log\\TrayData" + string.Format(@"\{0}", vDst.ToString());

            string[] tSourceFiles = Directory.GetFiles(tSource);
            if (string.IsNullOrEmpty(vDst) || tSourceFiles.Length < 1)
            {
                return;
            }

            if (!Directory.Exists(tDst))
            {
                Directory.CreateDirectory(tDst);
            }

            for (int i = 0; i < tSourceFiles.Length; i++)
            {
                String src = tSourceFiles[i];
                File.Copy(src, src.Replace(tSource, tDst), true);
            }
        }

        /// <summary>
        /// Log记录
        /// </summary>
        /// <param name="str">记录内容</param>
        /// <param name="filename">文件名称</param>
        public void WriteLog(string str, string filename)
        {
            string strlog = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") + ":" + str + "\r\n";
            string filePath = $"E:\\Log";
            string FileName = string.Format("{0}.txt", filename.ToString());

            if (Directory.Exists(filePath) == false)
            {
                Directory.CreateDirectory(filePath);
            }
            if (File.Exists(filePath + string.Format(@"\{0}", FileName)) == false)
            {
                File.Create(filePath + string.Format(@"\{0}", FileName)).Close();
            }

            FileStream fs = new FileStream(filePath + string.Format(@"\{0}", FileName), FileMode.Append, FileAccess.Write);
            //获取字节数组
            byte[] data = System.Text.Encoding.Default.GetBytes(strlog);
            //开始写入
            fs.Write(data, 0, data.Length);
            //清空缓冲区，关闭流
            fs.Flush();
            fs.Close();
        }
    }
}